<?php

namespace App\Services\Oms;

use App\Exceptions\JavaApiException;
use App\Services\Base;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ApiService extends Base
{
    /**
     * @return string
     */
    public function requestOMS(array $data,$method='post')
    {
        $data['app_key'] = env("OMS_APP_KEY");
        $data['timestamp'] = time();
        $data['random'] = mt_rand(10000000,99999999);
        $data['format'] = 'json';
        $data['version'] = '1.0';
        //获取签名
        $data['sign'] = $this->sign($data);
        $url = env("OMS_API_BASE_URL");
        Log::info('请求oms参数：'.json_encode($data));
        Log::info('请求OMS的URL：'.$url);

        $response = Http::timeout(5)->asForm()
//            ->contentType('application/x-www-form-urlencoded')
            ->$method($url, $data);
        $response->throw();

        $result = $response->json();

        Log::info('oms请求参数：'.json_encode($data));
        Log::info('url:'.$url.',请求方法：'.$method.',请求结果：'.json_encode($result));

        if (empty($result['code'] || $result['code'] != 200)){

            $msg = $url."发生错误，错误码："
                . "{$result['code']}，错误消息：{$result['message']}";
            Log::error($msg);
            throw new JavaApiException($result['message'],$result['code']);

        }

        return $result;
    }

    public function sign($data)
    {
        $stringA='';
        ksort($data,2);//键名进行升序排序(全部以字符类型排序)
        foreach($data as $k=>$v){//使用URL键值对生成stringA
            $stringA.=$k.'='.$v.'&';
        }
        $stringA.=env("OMS_SECRET_KEY");
        return strtoupper(md5($stringA));
    }

}